from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import async_to_sync
import json
from rtchannel.decoder2 import DecoderPipeline2
import rtchannel.conf as conf

class ChatConsumer(AsyncWebsocketConsumer):
    def __init__(self,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.decoder_pipeline = DecoderPipeline2({"decoder": conf.decoder_conf})
        self.final_hyps = []
        self.finished = False
        self.decoder_pipeline.set_result_handler(self.result_getter)
        self.decoder_pipeline.set_eos_handler(self.set_finished)

    async def connect(self):  # 连接时触发
        self.room_name = self.scope['url_route']['kwargs']['service_uid']
        self.room_group_name = 'notice_%s' % self.room_name  # 直接从用户指定的房间名称构造Channels组名称，不进行任何引用或转义。
        # 将新的连接加入到群组
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    def result_getter(self,hyp,final):
        if final:
            self.final_hyps.append(hyp)

    def set_finished(self,finished):
        self.finished = True

    async def disconnect(self, close_code):  # 断开时触发
        self.decoder_pipeline.end_request()
        self.decoder_pipeline.cancel()
        # 将关闭的连接从群组中移除
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data=None, bytes_data=None):  # 接收消息时触发
        # text_data_json = json.loads(text_data)
        # message = text_data_json['message']
        message = bytes_data
        # 信息群发
        self.decoder_pipeline.process_data(message)
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'system_message',
                'message': self.final_hyps
            }
        )

    # Receive message from room group
    async def system_message(self, event):
        message = event['message']

        # Send message to WebSocket单发消息
        await self.send(text_data=json.dumps({
            'message': message
        }))

